package com.mlethe.library.keyboard;

import android.content.Context;

import java.util.List;

/**
 * 字母键盘
 * @author Mlethe
 */
public class WordKeyboard extends Keyboard {
    public static boolean isUpper = false;
    private boolean isChange = false;

    public WordKeyboard(Context context) {
        super(context, R.xml.keyboard_word);
    }

    @Override
    protected boolean onKey(int primaryCode) {
        if (primaryCode == android.inputmethodservice.Keyboard.KEYCODE_SHIFT) {
            // 大小写切换
            isChange = true;
            changeKeyboard();
            switchKeyboard(WordKeyboard.class);
            return true;
        } else if(primaryCode == -2) {
            // 数字切换
            isChange = false;
            switchKeyboard(NumKeyboard.class);
            return true;
        }else if (primaryCode == 100860) {
            // 符号切换
            isChange = false;
            switchKeyboard(SymbolKeyboard.class);
            return true;
        }
        return false;
    }

    /**
     * 切换大小写
     */
    private void changeKeyboard() {
        List<Key> keyList = getKeys();
        if (isUpper) {
            // 大写切换小写
            isUpper = false;
            for (Key key : keyList) {
                if (key.label != null && isLetter(key.label.toString())) {
                    key.label = key.label.toString().toLowerCase();
                    key.codes[0] = key.codes[0] + 32;
                }
            }
        } else {
            // 小写切换成大写
            isUpper = true;
            for (Key key : keyList) {
                if (key.label != null && isLetter(key.label.toString())) {
                    key.label = key.label.toString().toUpperCase();
                    key.codes[0] = key.codes[0] - 32;
                }
            }
        }
    }

    /**
     * 判断是否是字母
     */
    private boolean isLetter(String str) {
        String wordStr = "abcdefghijklmnopqrstuvwxyz";
        return wordStr.contains(str.toLowerCase());
    }

    @Override
    public boolean isRandom() {
        if (isChange) {
            return false;
        }
        return true;
    }
}
